<template>
  <view class="flex-col">
    <view :class="boole ? 'bottom115' : ''">
      <!--基础信息-->
      <basic-info v-model="detailForm" :boole="boole" ref="refBasicInfo"/>

      <!--保养信息-->
      <upkeep-info v-model="detailForm" :boole="boole" ref="refUpkeepInfo"/>

      <!--保养项目明细-->

      <view class="item-wrap" style="margin-bottom: 0">
        <view class="lineBottom10">
          <uni-section title="保养项目明细" type="line"/>
        </view>

        <view style="margin: 8rpx 0 30rpx 20rpx">
          <uni-forms ref="detailForm" :rules="rules" :model="detailForm" label-position="top">
            <view style="margin-bottom: 20rpx">
              <text style="font-size: 40rpx; font-weight: 700">费用合计:</text>
              <text style="font-size: 40rpx; font-weight: 700">{{ `￥${detailForm.maintainQuoter}` }}</text>
            </view>

            <view style="display: flex; justify-content: flex-start; align-items: center; margin-bottom: 20rpx">
              <text style="font-size: 36rpx">保养项目明细</text>
              <button v-if="boole" class="uni-button add-button" size="mini" type="primary" @click="addDecoration">
                添加
              </button>
            </view>

            <uni-table ref="table" border stripe emptyText="暂无更多数据">
              <uni-tr>
                <uni-th width="70" align="center" v-if="boole">操作</uni-th>
                <uni-th width="130" align="center">保养项目名称</uni-th>
                <uni-th width="120" align="center">金额/元</uni-th>
                <uni-th width="150" align="center">详细信息</uni-th>
              </uni-tr>
              <uni-tr v-for="(item, index) in detailForm.carMaintainProjectList" :key="index">
                <uni-td v-if="boole">
                  <view style="display: flex; justify-content: center; align-items: center">
                    <button class="uni-button del-but" size="mini" @click="delDecoration(item, index)" type="warn">
                      删除
                    </button>
                  </view>
                </uni-td>
                <uni-td align="center">
                  <uni-easyinput v-if="boole" v-model="item.maintainName"/>
                  <text v-else>{{ item.maintainName || '-' }}</text>
                </uni-td>

                <uni-td align="center">
                  <uni-easyinput v-if="boole" v-model="item.price"
                                 @blur="blurTable(item, 'price')"
                                 @clear="clear(item, 'price')"/>
                  <text v-else>{{ item.price || 0 }}</text>
                </uni-td>

                <uni-td align="center">
                  <uni-easyinput v-if="boole" v-model="item.detailedInfo"/>
                  <text v-else>{{ item.detailedInfo || '-' }}</text>
                </uni-td>
              </uni-tr>
            </uni-table>

            <uni-forms-item name="maintainProjectUrl" label="上传附件:" :required="boole">
              <text class="maintainProjectUrl"/>
              <image-common :disabled="!boole" :up-type="2" v-model="detailForm.maintainProjectUrl"/>
            </uni-forms-item>
          </uni-forms>
        </view>
      </view>

      <!--审批流程-->
      <exam-flow v-if="flowId" :instanceId="flowId"/>
    </view>


    <view class="button-container" v-if="boole">
      <button class="btn-item" @click="submit">提 交</button>
    </view>
  </view>
</template>

<script>
import basicInfo from './components/basicInfo.vue'
import upkeepInfo from './components/upkeepInfo.vue'
import {getFindCarWorkOrderInfoVo, addMaintain, getMaintain} from '@/api/maintain/maintainList'

export default {
  name: 'add',
  components: {basicInfo, upkeepInfo},
  computed: {},
  watch: {
    'detailForm.maintainProjectUrl': {
      handler(val) {
        if (val) {
          this.$refs.detailForm.clearValidate(['maintainProjectUrl'])
        }
      },
      deep: true,
    },
  },
  data() {
    return {
      detailForm: {
        vinNo: "",
        carNo: "",
        brandName: "",
        seriesName: "",
        modelName: "",
        belongCityName: "",
        orderNo: "",
        leaseNum: "",
        customerName: "",
        leaseStartTime: "",
        leaseEndTime: "",
        totalBudgetPrice: "",

        registerTime: "",
        bicycleBudgetPrice: "",
        replacePrice: "",
        carSurplusPrice: "",

        workId: "",
        travelMeligile: "",
        businessDataId: "",
        expectStartTime: "",
        expectEndTime: "",
        maintainShop: "",
        maintainShopId: '',
        faultDescribe: "",
        maintainQuoter: "",
        reasonForClaim: "",
        carId: "",
        claimantReason: "",
        swappingAccessories: "",
        comprehensiveRecommendations: "",
        maintainRemark: "",
        licensePlateTime: "",
        carMaintainProjectList: [],
        maintainProjectUrl: "",

        //资金部反馈
        actualStartTime: "",
        actualEndTime: "",
        feedbackAdvancePayment: "",
        payType: "",
        maintainCompleteUrl: "",
        balanceUrl: "",
        maintainFeedback: "",
      },
      boole: false,
      flowId: null,
      rules: {
        maintainProjectUrl: {
          rules: [
            {
              required: true,
              errorMessage: '上传附件',
              validateTrigger: 'bind',
            },
          ],
        },
      },
    }
  },
  onLoad(op) {
    let title = ''
    this.flowId = op?.flowId
    console.log(op)
    if (op?.type === 'edit') {
      this.handleGetFindCarWorkOrderInfoVo(op?.id)
      title = '新增保养工单'
      this.boole = true
      if (op.businessDataId &&  op.businessDataId !== 'null') {
        this.handleGetMaintain(op?.businessDataId, op?.id)
      }
    }
    if (op?.type === 'view') {
      title = '保养工单详情'
      if (op?.businessDataId) {
        this.handleGetMaintain(op?.businessDataId, op?.id)
      }
      this.boole = false
    }

    this.detailForm.carId = op?.carId
    uni.setNavigationBarTitle({
      title,
    })
  },
  created() {
  },
  mounted() {
  },
  methods: {
    //处理按钮详情数据
    handleGetFindCarWorkOrderInfoVo(id) {
      getFindCarWorkOrderInfoVo(id).then((res) => {
        if (res.code === 200) {
          for (let key in res.data) {
            this.$set(this.detailForm, key, res.data[key])
          }
          this.detailForm.maintainQuoter = res.data.maintainQuoter || 0
          this.detailForm.workId = res.data?.workId || id
        }
      })
    },

    //详情数据
    handleGetMaintain(id, ids) {
      getMaintain(id).then((res) => {
        if (res.code === 200) {
          this.detailForm = res.data
          this.detailForm.workId = ids
        }
      })
    },

    async submit() {
      try {

        let effectPromises = [this.$refs.refBasicInfo.handleEffect(), this.$refs.refUpkeepInfo.handleEffect(), this.handleEffect()]

        // 等待所有效果处理完成
        await Promise.all(effectPromises)
        // 显示加载状态
        uni.showLoading()

        // 发送维护请求
        const res = await addMaintain(this.detailForm)

        if (res.code === 200) {
          uni.$emit("refBackList", true);
          this.$modal.msgSuccess("提交成功");
          setTimeout(() => {
            this.$tab.navigateBack();
          }, 1000);
        }
      } catch (error) {
        if (typeof error === 'string') {
          this.$nextTick(() => {
            uni.pageScrollTo({
              selector: error,
            })
          })
        } else {
          console.error(error)
        }
      } finally {
        setTimeout(() => {
          uni.hideLoading()
        }, 1000)
      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm
            .validate()
            .then((res) => {
              resolve()
            })
            .catch((err) => {
              reject('.maintainProjectUrl')
            })
      })
    },

    addDecoration() {
      let obj = {
        maintainName: '',
        detailedInfo: '',
        price: '',
      }
      this.detailForm.carMaintainProjectList.push(obj)
      this.handleCount()
    },

    //删除保养项目明细
    delDecoration(row, key) {
      this.detailForm.carMaintainProjectList.splice(key, 1)
      this.handleCount()
    },

    blurTable(row, field) {
      const reg = /^(?:[1-9]\d*|0)(?:\.\d{0,2})?$/
      const match = row[field].toString().match(reg)
      row[field] = match ? match[0] : ''
      this.handleCount()
    },

    clear(row, field) {
      row[field] = ''
      this.handleCount()
    },

    handleCount() {
      if (this.detailForm.maintainType === '1') {
        this.detailForm.maintainQuoter = 0
      } else if (this.detailForm.maintainType === '2') {
        let num = 0
        for (let i = 0; i < this.detailForm.carMaintainProjectList.length; i++) {
          num += Math.round(Number(this.detailForm.carMaintainProjectList[i].price) * 100)
        }
        this.detailForm.maintainQuoter = (num / 100).toFixed(2)
      }
    },

  },
}
</script>

<style scoped lang="scss">
.add-button {
  margin-left: 20rpx;
}

.del-but {
  padding-right: 20rpx;
  padding-left: 20rpx;
}
</style>
